package com.cms.util;

import java.io.*;
import java.util.List;

import com.aliyun.oss.model.*;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

import com.aliyun.oss.OSSClient;
import com.cms.Config;
/**
 *
 * OSS 工具类
 */
public class OSSUtils {

    public static void upload(String path, File file, String contentType){
    	Config config = SystemUtils.getConfig();
        String endpoint = config.getOss_endpoint();    // Endpoint以杭州为例，其它Region请按实际情况填写。
        String accessId = config.getOss_accessId();    //AccessKey ID
        String accessKey = config.getOss_accessKey();   //Access Key Secret    
        String bucketName = config.getOss_bucket();  //桶名称
        InputStream inputStream = null;
        try {
            inputStream = new BufferedInputStream(new FileInputStream(file));
            OSSClient ossClient = new OSSClient(endpoint, accessId, accessKey);
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType(contentType);
            objectMetadata.setContentLength(file.length());
            ossClient.putObject(bucketName, StringUtils.removeStart(path, "/"), inputStream, objectMetadata);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
    }

    public static void test() throws IOException {
        String nextMarker = null;
        ObjectListing objListing;
        OSSClient ossClient = new OSSClient("oss-cn-hongkong.aliyuncs.com", "LTAI4G53WtS64QK3RP29Jdui", "Hgj6F0bEvN82j33D2d520jM4wwcMTQ");
        do {
            if (nextMarker == null) // 第一次的分页
                objListing = ossClient.listObjects(new ListObjectsRequest("jreshophk").withMaxKeys(1000));
            else // 以后的分页，附带nextMarker
                objListing = ossClient.listObjects(
                        new ListObjectsRequest("jreshophk").withMarker(nextMarker).withMaxKeys(1000));

            List<OSSObjectSummary> sums = objListing.getObjectSummaries();
            for (OSSObjectSummary s : sums)
            {
                String ossKey = s.getKey();
                OSSObject ossObject = ossClient.getObject("jreshophk",ossKey);
                IOUtils.copy(ossObject.getObjectContent(),new FileOutputStream(new File("C:/images/"+ossKey)));
            }
            // 下一次分页的nextMarker
            nextMarker = objListing.getNextMarker();
        } while (objListing.isTruncated());
    }
}
